package com.example.lab01.controller;

import com.example.lab01.entity.User;
import com.example.lab01.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.net.http.HttpClient;
import java.util.List;

@Controller
@RequestMapping("user")
public class UserController extends BaseController {
    @Autowired
    private UserService userService;


    @PostMapping("create")
    public String create(@RequestBody User u) {
        System.out.println(u);
        userService.create(u);
        return "redirect:queryAll";
    }

    //   @GetMapping("queryAll")
//    public ModelAndView queryAll(){
//       ModelAndView modelAndView = new ModelAndView();
//       List<User> userList = userService.queryAll();
//       modelAndView.addObject("user",userList);
//       modelAndView.setViewName("index.html");
//       return modelAndView;
//   }
    @GetMapping("queryAll")
    public String queryAll(Model model) {
        List<User> userList = userService.queryAll();
        model.addAttribute("users", userList);
        return "user";
    }

    //@GetMapping("queryAll")
//@ResponseBody//返回json格式 {}object是对象，[]为array数组
//public List<User> queryAll(Model model){
//
//    return userService.queryAll();
//}
    @GetMapping("queryById/{id}")
    public String queruById(@PathVariable int id, Model model) {
        model.addAttribute("user", userService.queryById(id));
        User u = userService.queryById(id);
        session.setAttribute("id", u.getId());
        return "edit";
    }

    @PostMapping("modify")
    public String modify(User u) {
        u.setId((Integer) session.getAttribute("id"));
        userService.modify(u);
        return "redirect:queryAll";
    }

    //    @GetMapping ("removeById/{id}")
//    public String removeById(@PathVariable int id,Model model){
//       userService.removeById(id);
//       model.addAttribute("users",userService.queryAll());
//        return "user";
//    }
//getmapping不可以用重定向方法
    @GetMapping("removeById/{id}")
    public String removeById(@PathVariable int id, Model model) {
        userService.removeById(id);
        model.addAttribute("users", userService.queryAll());
        return "user";
    }
}
